package public

import (
	"booking/common/handler"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// 生成随机 64 位字符串（32字节 -> 64个十六进制字符）
func randomFileName() (string, error) {
	bytes := make([]byte, 32)
	if _, err := rand.Read(bytes); err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

func UploadFile(c *gin.Context) {
	// 获取上传文件
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "获取文件失败: " + err.Error()})
		return
	}

	// 获取文件后缀（并转小写）
	ext := strings.ToLower(filepath.Ext(file.Filename))
	if ext == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "上传文件无后缀"})
		return
	}

	// 限制允许的文件类型（图片常见类型）
	allowedExt := map[string]bool{
		".jpg":  true,
		".jpeg": true,
		".png":  true,
		".gif":  true,
		".webp": true,
	}
	if !allowedExt[ext] {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("不支持的文件类型: %s", ext)})
		return
	}
	originalName := file.Filename
	// 创建日期分目录路径
	now := time.Now()
	dirPath := fmt.Sprintf("/www/wwwroot/static/%04d/%02d/%02d", now.Year(), now.Month(), now.Day())
	//dirPath := fmt.Sprintf("/Users/lims/lims/golang/%04d/%02d/%02d", now.Year(), now.Month(), now.Day())

	// 确保目录存在
	if err := os.MkdirAll(dirPath, 0755); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建目录失败: " + err.Error()})
		return
	}

	// 生成随机文件名
	randomName, err := randomFileName()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成随机文件名失败: " + err.Error()})
		return
	}

	// 拼接完整路径
	savePath := filepath.Join(dirPath, randomName+ext)

	urlPath := viper.GetString("staticUrl") + filepath.Join(fmt.Sprintf("/%04d/%02d/%02d", now.Year(), now.Month(), now.Day()), randomName+ext)

	// 保存文件
	if err := c.SaveUploadedFile(file, savePath); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "文件保存失败: " + err.Error()})
		return
	}
	handler.Success(map[string]any{
		"name": originalName,
		"url":  urlPath,
	}, c)
}
